<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\CustomerRequest;
use App\Models\V1\BasicCollectors;
use App\Models\V1\BasicCustomers;
use App\Models\V1\BasicTransformers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Log;

class CustomersController extends Controller
{
    /**
     * 显示教职工数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.customers');
    }

    /**
     * 获取教职工数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的客户数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的客户数据
        $data = $this->getCustomersList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['contact'] = $item['contact'];
                    $formatItem['mobile'] = $item['mobile'];
                    $formatItem['telephone'] = $item['telephone'];
                    $formatItem['fax'] = $item['fax'];
                    $formatItem['email'] = $item['email'];
                    $formatItem['address'] = $item['address'];
                    $formatItem['contract_sign_date'] = $item['contract_sign_date'];
                    $formatItem['serve_time_limit'] = empty($item['serve_time_limit']) ? "" : $item['serve_time_limit'].'年';
                    $formatItem['inspection_date'] = $item['inspection_date'];
                    $formatItem['expire_remind_time'] = empty($item['expire_remind_time']) ? "" : $item['expire_remind_time'].'天';
                    $formatItem['inspection_remind_time'] =  empty($item['inspection_remind_time']) ? "" : $item['inspection_remind_time'].'天';
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条客户数据显示界面（适用于新增addData、查看viewData、编辑editData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')){
            case 'addData':
                $data['randomCode'] = 'CSR' . uniqid();
                $data['expireTimes'] = $this->getExpireRemindTimeList();
                $data['inspectionTimes'] = $this->getInspectionRemindTimeList();
                return view('v1.form.customer_item', $data);
                break;
            case 'editData':
                $data['code'] = $request->input('code');
                $data['expireTimes'] = $this->getExpireRemindTimeList();
                $data['inspectionTimes'] = $this->getInspectionRemindTimeList();
                $customer = $this->getCustomerByCode($data['code']);
                $data['itemData'] = $customer;
                return view('v1.form.customer_item', $data);
                break;
            case 'viewData':
                $data['code'] = $request->input('code');
                $customer = $this->getCustomerByCode($data['code']);
                $data['itemData'] = $customer;
                return view('v1.form.customer_item', $data);
                break;

        }
    }

//    /**
//     * 显示教职工数据导入页面
//     *
//     * @param Request $request
//     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
//     */
//    public function importView(Request $request)
//    {
//        // 获取登录用户
//        $loginUser = Auth::user();
//
//        $data['view'] = $request->input('view');
//        $data['code'] = $loginUser->getAttribute('code');
//
//        return view('v1.form.upload_excel', $data);
//    }

    /**
     * 更新客户基本信息(单元格)
     *
     * @param CustomerRequest $request
     * @return array
     */
    public function updateCellData(CustomerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '客户代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCustomer($request);

            // 更新客户信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '客户代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '客户[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
//            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '客户代码不能为空';
            $messages['name.required'] = '客户姓名不能为空';
//            $messages['captcha.required'] = '验证码不能为空';
//            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '客户[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 更新客户基本信息
     *
     * @param CustomerRequest $request
     * @return array
     */
    public function updateData(CustomerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '客户代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCustomer($request);

            // 更新教职工信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '客户代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 删除客户基本信息
     *
     * @param CustomerRequest $request
     * @return array
     */
    public function deleteData(CustomerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '客户代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCustomer($request);

            // 删除客户信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '客户代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除客户基本信息
     *
     * @param CustomerRequest $request
     * @return array
     */
    public function deleteBatchData(CustomerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '客户批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除教职工信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '客户批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的客户列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getCustomersList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = BasicCustomers::orderBy('created_at', 'asc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = BasicCustomers::where('name', 'like', '%' . $keywords . '%')->orderBy('created_at', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 设置到期前多少天提醒的选择列表
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getExpireRemindTimeList()
    {
        $t1 = array('code'=>'3','value'=>'前3天');
        $t2 = array('code'=>'5','value'=>'前5天');
        $t3 = array('code'=>'10','value'=>'前10天');
        $t4 = array('code'=>'15','value'=>'前15天');
        $remindTimes = array($t1,$t2,$t3,$t4);
        return $remindTimes;
    }

    /**
     * 设置巡检时间提前多少天提醒的选择列表
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getInspectionRemindTimeList()
    {
        $t1 = array('code'=>'2','value'=>'前2天');
        $t2 = array('code'=>'3','value'=>'前3天');
        $t3 = array('code'=>'5','value'=>'前5天');
        $t4 = array('code'=>'10','value'=>'前10天');
        $remindTimes = array($t1,$t2,$t3,$t4);
        return $remindTimes;
    }

    /**
     * 根据教职工代码获取对应教职工信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCustomerByCode($code)
    {
        $customer = BasicCustomers::where('code', $code)->first();
        return $customer;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新教职工信息验证请求
     *
     * @param Request $request
     */
    private function validateCustomer(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新客户信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
            ];
            if ($request->input('contact') !== "") {
                $updateData['contact'] = $request->input('contact');
            }
            if ($request->input('mobile') !== "") {
                $updateData['mobile'] = $request->input('mobile');
            }
            if ($request->input('email') !== "") {
                $updateData['email'] = $request->input('email');
            }
            if ($request->input('telephone') !== "") {
                $updateData['telephone'] = $request->input('telephone');
            }
            if ($request->input('fax') !== "") {
                $updateData['fax'] = $request->input('fax');
            }
            if ($request->input('address') !== "") {
                $updateData['address'] = $request->input('address');
            }
            if ($request->input('contract_sign_date') !== "") {
                $updateData['contract_sign_date'] = $request->input('contract_sign_date');
            }
            if ($request->input('serve_time_limit') !== "") {
                $updateData['serve_time_limit'] = $request->input('serve_time_limit');
            }
            if ($request->input('inspection_date') !== "") {
                $updateData['inspection_date'] = $request->input('inspection_date');
            }
            if ($request->input('expire_remind_time') !== "") {
                $updateData['expire_remind_time'] = $request->input('expire_remind_time');
            }
            if ($request->input('inspection_remind_time') !== "") {
                $updateData['inspection_remind_time'] = $request->input('inspection_remind_time');
            }
        }

        $rspObj = BasicCustomers::where('code', $where)
            ->update($updateData);

        return $rspObj;
    }

    /**
     * 处理更新客户工信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        // 开启事务
        DB::beginTransaction();
        $where = $request->input('code');
        // 全部删除的标志,0:默认值，1：删除失败， 2全部删除成功
        $allDeleteTag = '0';
        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');
            foreach ($codeList as $code) {
                $deleteTag = $this->deleteCustomer($code);
                if (!$deleteTag){
                    $allDeleteTag = '1';
                    break;
                }else{
                    $allDeleteTag = '2';
                }
            }
            //全部成功删除时，事务commit
            if ($allDeleteTag === '2'){
                DB::commit();
                return true;
            }else{
                DB::rollBack();
                return false;
            }

        } else { // 单条删除
            $deleteTag = $this->deleteCustomer($where);
            if (!$deleteTag){
                DB::rollBack();
                return false;
            }else{
                DB::commit();
                return true;
            }
        }
    }

    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
            'contact' => isset($request['contact']) ? $request->input('contact') : NULL,
            'mobile' => isset($request['mobile']) ? $request->input('mobile') : NULL,
            'telephone' => isset($request['telephone']) ? $request->input('telephone') : NULL,
            'fax' => isset($request['fax']) ? $request->input('fax') : NULL,
            'email' => isset($request['email']) ? $request->input('email') : NULL,
            'address' => isset($request['address']) ? $request->input('address') : NULL,
            'contract_sign_date' => isset($request['contract_sign_date']) ? $request->input('contract_sign_date') : NULL,
            'serve_time_limit' => isset($request['serve_time_limit']) ? $request->input('serve_time_limit') : NULL,
            'inspection_date' => isset($request['inspection_date']) ? $request->input('inspection_date') : NULL,
            'expire_remind_time' => isset($request['expire_remind_time']) ? $request->input('expire_remind_time') : NULL,
            'inspection_remind_time' => isset($request['inspection_remind_time']) ? $request->input('inspection_remind_time') : NULL,
        ];

        $rspObj = BasicCustomers::create($insertData);

        return $rspObj;
    }

    /**
     *  处理客户的删除，删除关联表的相关数据
     * @param Request $request
     * @return bool
     */
    private function deleteCustomer($code)
    {
        $allDeleteTag = '1';
        $customerObj = BasicCustomers::where('code',$code)->first();
        if (!empty($customerObj)) {
            // 查询变压器是否关联了此客户，如果关联了则删除
            $transformerObj = BasicTransformers::where('customer_code',$code)->get();
            if ($transformerObj) {
                foreach ($transformerObj as $transformer) {
                    // 查询是否有采集器关联了此变压器
                    $collectorObj = BasicCollectors::where('transformer_code',$transformer['code'])->first();
                    if ($collectorObj) {
                        // 删除采集器
                        $collectorDeleteTag = $collectorObj->delete();
                        if (!$collectorDeleteTag){
                            return false;
                        }else{
                            $allDeleteTag = '2';
                        }
                    }else{
                        $allDeleteTag = '2';
                    }

                    // 删除变压器
                    if ($allDeleteTag === '1'){
                        return false;
                    }else{
                        $transformerTag = $transformer->delete();
                        if (!$transformerTag){
                            return false;
                        }else{
                            $allDeleteTag = '2';
                        }
                    }
                }
            }else{
                $allDeleteTag = '2';
            }

            //删除客户
            if ($allDeleteTag === '1'){
                return false;
            }else{
                $customerTag = $customerObj->delete();
                if (!$customerTag){
                    return false;
                }else{
                    return true;
                }
            }

        }else{
            return false;
        }
    }
}
